#include "temperature.h"
#include <stdlib.h>


//TODO: move array to progmem
uint8_t search(uint16_t target){
	//vref=2.56 bandgap
	//first value =105C
	//last =-13C
	const static uint16_t temperature[]={ \
		27,28,29,30,31,32,33,34,35,36, \
		37,38,39,41,42,43,45,46,48,50, \
		51,53,55,57,58,60,63,65,67,69, \
		72,74,77,80,82,85,88,91,95,98, \
		101,105,109,113,117,121,125,130, \
		135,140,145,150,155,161,167,173, \
		179,186,193,200,207,214,222,230, \
		239,247,256,265,275,284,294,305, \
		316,327,338,349,361,374,386,399, \
		413,426,440,454,469,483,498,514, \
		529,545,561,577,594,610,627,644, \
		661,678,696,713,730,748,765,782, \
		800,817,834,851,867,884,900,916, \
		932,948,963,978,993,1007,1021 \
		};

	const uint8_t length = 119;

    uint8_t last, begin, end, i;
    end =length-1;
    begin = 0;
    i = length/2;
    last = 0;

    // WARNING! Ugly code ahead
    while (temperature[i]!=target) {
        if (abs(i-last)<1){
            int tmp1,tmp2,tmp3;
            tmp1=abs(target-temperature[i-1]);
            tmp2=abs(target-temperature[i]);
            tmp3=abs(target-temperature[i+1]);
            if(tmp2<tmp1 && tmp2<tmp3) {
                return i;
            } else if (tmp3<tmp1) {
                return i==length?i:i+1;
			} else {
				// return i, underflow
            	return i?i-1:0;
			}
        }

        last = i;

        if(target < temperature[i] && i != 0){
            end=i-1; 
        } else if (i != 0xff) {
            begin =i+1;
        }
		i = begin + (end-begin)/2;
    }
    return i;

}

int8_t adc2temp(uint16_t adcValue){
	return (105-search(adcValue));

}
